<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
      <el-form-item label="客户名称" prop="customerNickName">
        <el-input v-model="queryParams.customerNickName" placeholder="请输入客户名称" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="客户编码" prop="customerId">
        <el-input v-model="queryParams.customerId" placeholder="请输入客户编码" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchReset">重置</el-button>
      </el-form-item>

    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:role:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:role:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:role:edit']"
        >修改
        </el-button>
      </el-col>
    </el-row>

    <el-table v-loading="loading" :data="roleList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="id" prop="id" width="250" v-if="false"/>
      <el-table-column label="客户名称" prop="customerNickName" align="center"/>
      <el-table-column label="编码" prop="customerId"align="center" />
      <el-table-column label="操作" align="center" width="260" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            size="small"
            type="text"
            @click="handleViewAttachments(scope.$index, scope.row)"
          >查看合同
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/修改弹窗 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1000px"
      append-to-body
      class="contract-dialog"
      @close="cancel"
    >
      <el-form ref="form" :model="form" :rules="rules" class="compact-form">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="客户编码" prop="customerId" class="form-item-compact">
              <el-input v-model="form.customerId" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="客户名称" prop="customerNickName" class="form-item-compact">
              <el-input v-model="form.customerNickName" placeholder="请输入客户名称" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 查看合同弹窗 -->
    <el-dialog :title="title" :visible.sync="attachmentWindow" width="600px" append-to-body @close="cancel">
      <el-form ref="form" :model="form" label-width="80px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="附件" prop="attachments">
              <el-upload
                :action="attachmentUpload.url"
                :headers="attachmentUpload.headers"
                :on-success="handleAttachmentSuccess"
                :before-upload="beforeAttachmentUpload"
                :on-remove="handleRemoveAttachment"
                :file-list="attachmentListShow"
                :limit="5"
                multiple
                list-type="text">
                <el-button type="primary" size="small">点击上传</el-button>
                <div slot="tip" class="el-upload__tip">
                  可上传图片、Excel、PDF、Word文件，单个文件不超过10MB
                </div>
              </el-upload>

              <!-- 文件预览区域 -->
              <div class="file-preview-container">
                <div v-for="(file, index) in attachmentListShow" :key="index" class="file-item">
                  <div @click="handlePreview(file)">
                    <i :class="getFileIcon(file.type)" style="margin-right: 5px;"></i>
                    <span>{{ file.name }}</span>
                  </div>
                </div>
              </div>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <!-- 图片预览弹窗 -->
      <el-dialog :visible.sync="imagePreviewVisible" append-to-body>
        <img width="100%" :src="previewImageUrl" alt="">
      </el-dialog>

      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFormAttachments">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />
  </div>

</template>

<script>

import {getList,addOrUpdate,deleteByIds} from '@/api/amac/customerContract/customerContract'
import {
  getPerformanceAttachments,
  updateAttachments,
  uploadAttachment
} from '@/api/amac/customerContract/customerContract'
import {getToken} from "@/utils/auth"

export default {
  name: "Role",
  dicts: ['sys_normal_disable'],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 角色表格数据
      roleList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示弹出层（数据权限）
      openDataScope: false,
      menuExpand: false,
      menuNodeAll: false,
      deptExpand: true,
      deptNodeAll: false,
      pictureDetails: false,  // 控制弹窗显示
      srcList: [],  // 存储图片路径的数组
      currentIndex: 0,  // 当前显示图片的索引
      // 菜单列表
      menuOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        customerNickName: undefined,
        customerId: undefined,
      },
      dialogImageUrl: '',
      dialogVisible: false,
      // 图片数量限制
      limit: 3,
      //图片地址
      imageUrl: "",
      // 表单参数
      // 表单参数
      form: {},
      rules: {
        customerId: [
          { required: true, message: '请输入客户编码', trigger: 'blur' }
        ],
        customerNickName: [
          { required: true, message: '请输入客户名称', trigger: 'blur' }
        ]
      },
      // ... existing data properties ...
      selectedMonth: '', // 当前选择的月份
      submitting: false, // 控制提交按钮的加载状态
      // 新增附件相关数据
      attachmentWindow: false,
      attachmentUpload: {
        headers: {
          Authorization: "Bearer " + getToken()
        },
        url: process.env.VUE_APP_BASE_API + "/amac/departmentMerit/upload/attachment",
      },
      attachmentListShow: [],
      attachmentListPut: [],
      imagePreviewVisible: false,
      previewImageUrl: '',
      currentParentId: null,
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    // 🔽 页面加载时自动调用
  },
  methods: {
    // 取消按钮
    cancel() {
      this.open = false;
      this.attachmentWindow = false;
      this.reset();
      this.loading = false;
    },
    // 表单重置
    reset() {
      this.form =  {
        customerNickName: undefined,
        customerId: undefined,
      }
    },
    //
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList();
    },
    /** 重置按钮操作 */
    searchReset() {
      this.queryParams.pageNum = 1
      this.queryParams = {}
      this.getList();
    },
    /** 查询列表 */
    getList() {
      getList(this.queryParams).then(response => {
        if (!response.rows) return false
        this.roleList = response.rows
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 多选框选中数据 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length != 1
      this.multiple = !selection.length
    },
    handleAdd(){
      this.open = true;
      this.title = "新增合同信息";
    },
    handleUpdate(){
      const selected = this.roleList.find(item => item.id === this.ids[0]);
      if (!selected) return;

      this.form = { ...selected };  // 深拷贝到表单
      this.title = "修改合同信息";
      this.open = true;
    },
    handleDelete(){
      this.$confirm("确定要删除选中的数据吗？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        deleteByIds(this.ids).then(res => {
          this.$message.success("删除成功");
          this.getList();
        }).catch(() => {
          this.$message.error("删除失败");
        });
      }).catch(() => {
        // 用户点击取消
      });
    },
    /**
     * 新增和修改的确认按钮
     */
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          this.$message.error('请填写完整表单内容');
          return;
        }

        this.submitting = true;
        console.log("this.form.id", this.form.id);

        addOrUpdate(this.form)
          .then(res => {
            this.$message.success(this.form.id ? "修改成功" : "新增成功");
            this.open = false;
            this.getList();
          })
          .catch(error => {
            this.$message.error((this.form.id ? "修改失败" : "新增失败") + ": " + (error.message || "未知错误"));
          })
          .finally(() => {
            this.submitting = false;
          });
      });
    },
    //以下是附件处理方法

    handleViewAttachments(index, row) {
      this.currentParentId = row.id;
      this.loading = true;
      this.attachmentWindow = true;
      this.title = `查看合同 - ${row.customerNickName}`; // 使用客户名称作为标题

      const queryParams = {
        parentId: row.id
      };

      console.log("queryParams=",queryParams)
      getPerformanceAttachments(queryParams)
        .then(response => {
          if (!response?.data) {
            this.resetAttachmentLists();
            this.$message.info('暂无附件数据');
            return;
          }

          try {
            // 假设后端已直接返回结构化数据，不需要再parse
            const attachmentData = response.data;

            // 处理附件列表
            this.attachmentListShow = this.processAttachmentList(attachmentData);
            this.attachmentListPut = [...this.attachmentListShow];
          } catch (e) {
            console.error('处理附件数据失败:', e);
            this.resetAttachmentLists();
            this.$message.error('附件数据处理失败');
          }
        })
        .catch(error => {
          console.error('获取附件失败:', error);
          this.resetAttachmentLists();
          this.$message.error('获取附件失败: ' + (error.message || '请稍后重试'));
        })
        .finally(() => {
          this.loading = false;
        });
    },

// 辅助方法：处理附件列表
    processAttachmentList(attachmentData) {
      // 如果后端返回的是字符串形式，尝试解析
      const rawList = typeof attachmentData === 'string'
        ? JSON.parse(attachmentData)
        : attachmentData;

      // 确保是数组
      const attachmentList = Array.isArray(rawList) ? rawList : [];

      return attachmentList.map(item => ({
        url: item.url,
        name: item.name || this.extractFileNameFromUrl(item.url),
        type: item.type || this.getFileType(item.url)
      }));
    },

// 辅助方法：从URL提取文件名
    extractFileNameFromUrl(url) {
      if (!url) return '未知文件';
      try {
        return url.substring(url.lastIndexOf('/') + 1);
      } catch {
        return '未知文件';
      }
    },

// 辅助方法：重置附件列表
    resetAttachmentLists() {
      this.attachmentListShow = [];
      this.attachmentListPut = [];
    },

    // 获取文件类型
    getFileType(url) {
      const extension = url.split('.').pop().toLowerCase();
      if (['jpg', 'jpeg', 'png', 'gif'].includes(extension)) {
        return 'image';
      } else if (['xls', 'xlsx'].includes(extension)) {
        return 'excel';
      } else if (extension === 'pdf') {
        return 'pdf';
      } else if (['doc', 'docx'].includes(extension)) {
        return 'word';  // 新增word类型
      }
      return 'other';
    },

    // 附件上传前的校验
    beforeAttachmentUpload(file) {
      // const allowedTypes = ['image/jpeg', 'image/png', 'application/pdf',
      //   'application/vnd.ms-excel',
      //   'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'];
      const allowedTypes = [
        'image/jpeg', 'image/png',
        'application/pdf',
        'application/vnd.ms-excel',
        'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
        'application/msword',
        'application/vnd.openxmlformats-officedocument.wordprocessingml.document' // Word文档类型
      ];
      const isLt10M = file.size / 1024 / 1024 < 10;  // 改为10MB限制

      if (!allowedTypes.includes(file.type)) {
        this.$message.error('只能上传图片、PDF、Word或Excel文件!');
        return false;
      }
      if (!isLt10M) {
        this.$message.error('上传的文件不能超过10MB!');
        return false;
      }

      // 检查是否已存在同名文件
      if (this.attachmentListPut.some(item => item.name === file.name)) {
        this.$message.error('已存在同名文件!');
        return false;
      }

      return true;
    },

    // 附件上传成功处理
    handleAttachmentSuccess(res, file) {
      const baseUrl = process.env.VUE_APP_BASE_API
      const relativePath = res.data.url
      const fileType = this.getFileType(file.name);
      this.attachmentListPut.push({
        url: baseUrl + relativePath,
        name: file.name,
        type: fileType
      });
      this.$message.success('文件上传成功');
    },
    // 删除附件
    handleRemoveAttachment(file, fileList) {
      this.attachmentListPut = this.attachmentListPut.filter(item => item.url !== file.url);
    },
    // 提交附件
    submitFormAttachments() {
      const submitData = {
        date: this.selectedMonth,
        parentId: this.currentParentId,
        attachments: this.attachmentListPut
      };

      this.loading = true;
      updateAttachments(submitData)
        .then(response => {
          this.$message.success('附件保存成功');
          this.attachmentWindow = false;
        })
        .catch(error => {
          console.error('保存附件失败:', error);
          this.$message.error('保存附件失败');
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 获取文件图标
    getFileIcon(fileType) {
      switch(fileType) {
        case 'image':
          return 'el-icon-picture';
        case 'pdf':
          return 'el-icon-document';
        case 'excel':
          return 'el-icon-document';
        case 'word':
          return 'el-icon-document';  // Word文档图标
        default:
          return 'el-icon-document';
      }
    },

    // 处理预览
    handlePreview(file) {
      if (file.type === 'image') {
        // 图片预览
        this.previewImageUrl = file.url;
        this.imagePreviewVisible = true;
      } else {
        // 其他文件下载
        window.open(file.url, '_blank');
      }
    },

  },


};
</script>
<style>
/* 弹窗整体样式 */
.contract-dialog {
  font-family: "Microsoft YaHei", sans-serif;
}

/* 紧凑型表单样式 */
.compact-form {
  padding: 20px 30px;
}

/* 表单项样式 */
.form-item-compact {
  margin-bottom: 18px;
}
.form-item-compact .el-form-item__label {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  padding-right: 12px;
  color: #606266;
  font-weight: normal;
}
.form-item-compact .el-input {
  width: 100%;
  min-width: 180px;
}

/* 底部按钮样式 */
.dialog-footer {
  text-align: center;
  padding: 15px 0 0;
}
.dialog-footer .el-button {
  min-width: 100px;
  margin: 0 10px;
}

/* 响应式调整 */
@media (max-width: 1200px) {
  .contract-dialog {
    width: 90% !important;
  }
  .form-item-compact .el-input {
    min-width: 150px;
  }
}

/* Word文档特殊样式 */
.file-item .el-icon-document[data-file-type="word"] {
  color: #2b579a; /* Microsoft Word蓝色 */
}
</style>
